import React, { PureComponent, Fragment } from 'react';
import router from 'umi/router';
import { connect } from 'dva';
import moment from 'moment';
import TooltipIcon from '@/components/TooltipIcon';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Dropdown,
  Menu,
  InputNumber,
  DatePicker,
  Modal,
  message,
  Badge,
  Divider,
  Steps,
  Radio,
  Tooltip,
  Rate,
  Checkbox,
  Tag,
  Popover,
  Spin,
  Empty,
} from 'antd';
import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import Ellipsis from '@/components/Ellipsis';
import MyIcon from '@/components/MyIcon';
import IconButton from '@/components/IconButton';
import get from 'lodash/get';

import styles from './Manage.less';
import Link from 'umi/link';
import { stringify } from 'querystring';
import { SERVICE_STATUS } from '@/Constants';
import CreateUserForm from './CreateUser/CreateUser';
import UpdateUserForm from './UpdateUser/UpdateUser';
import OrgTree from './OrgTree/OrgTree';

const { Step } = Steps;
const { TextArea, Search } = Input;
const { Option } = Select;
const RadioGroup = Radio.Group;

@connect(({ user, base, product, org, loading }) => ({
  userList: user.userList,
  cargoTypes: base.cargoTypes,
  products: product.products,
  productGroups: product.productGroups,
  orgTree: org.orgTree,
  loading: loading.effects['user/queryUserList'],
  createLoading: loading.effects['user/add'],
  updateLoading: loading.effects['user/update'],
  deleteLoading: loading.effects['user/delete'],
  lockLoading: loading.effects['user/lock'],
  unlockLoading: loading.effects['user/unlock'],
  resetPwdLoading: loading.effects['user/resetPassword'],
}))
@Form.create()
class Manage extends PureComponent {
  state = {
    formValues: {},
    selectedRows: [],
    modalVisible: false,
    updateModalVisible: false,
    currentUser: {},
    selectedOrgKeys: [],
    roleList: null,
  };

  getColumns = () => [
    {
      title: '序号',
      // width: '100px',
      render: (text, record, index) => {
        return <span>{this.calcIndex(index)}</span>;
      },
    },
    {
      title: '账号',
      // width: '100px',
      dataIndex: 'userName',
      render: (text, record) => {
        return (
          <div
            style={{
              position: 'relative',
              display: 'flex',
              flexDirection: 'row',
              alignItems: 'center',
            }}
          >
            {record.isLocked && <TooltipIcon title="锁定" icon="iconoss---suo-suoding" />}
            <a onClick={() => this.handleUpdateModalVisible(true, record)}>{text}</a>
          </div>
        );
      },
    },
    {
      title: '姓名',
      // width: '100px',
      dataIndex: 'fullName',
    },
    {
      title: '手机',
      // width: '150px',
      dataIndex: 'mobilePhone',
    },
    {
      title: '邮箱',
      // width: '300px',
      dataIndex: 'email',
      render: (text, record, index) => {
        return (
          <Ellipsis tooltip length={20} className={styles.ellipsis}>
            {text}
          </Ellipsis>
        );
      },
    },
    {
      title: '角色',
      render: (text, record) => {
        const { roleList } = this.state;
        return (
          <Popover
            content={
              <Spin spinning={!roleList}>
                <div style={{ minHeight: '20px', minWidth: '80px' }}>
                  {roleList &&
                    (roleList.length === 0 ? (
                      <Empty description="暂无角色" />
                    ) : (
                      roleList.map(role => {
                        return (
                          <p key={role.id} style={{ margin: '14px 20px' }}>
                            {role.name}({role.code})
                          </p>
                        );
                      })
                    ))}
                </div>
              </Spin>
            }
            trigger="click"
            placement="leftBottom"
          >
            <a
              onClick={e => {
                this.handleQueryRole(record.id);
              }}
            >
              查看
            </a>
          </Popover>
        );
      },
    },
  ];

  async componentDidMount() {
    await this.queryOrgTree();
    const { orgTree } = this.props;
    this.setState({
      selectedOrgKeys: orgTree[0] ? [orgTree[0].id] : [],
    });
    this.searchUsers();
  }

  // 序号
  calcIndex = index => {
    const { userList } = this.props;
    let currentPage = get(userList, 'pagination.currentPage') || 1;
    let pageSize = get(userList, 'pagination.pageSize') || 50;
    return (currentPage - 1) * pageSize + index + 1;
  };

  handleQueryRole = async id => {
    this.setState({
      roleList: null,
    });
    let res = await this.queryRoles(id);
    if (res.errorCode === 0) {
      this.setState({
        roleList: res.data || [],
      });
    }
  };

  queryRoles = id => {
    const { dispatch } = this.props;
    return dispatch({
      type: 'user/queryRoles',
      payload: {
        pathParams: {
          id,
        },
      },
    });
  };

  queryOrgTree = () => {
    const { dispatch } = this.props;
    return dispatch({
      type: 'org/queryOrgTree',
    });
  };

  // 查找用户列表
  searchUsers = ({ q = '', pageIndex = 1, pageSize = 50, ...rest } = {}) => {
    const { dispatch, form } = this.props;
    form.validateFields((err, fieldsValue) => {
      let payload = {
        ...fieldsValue,
        pageIndex,
        pageSize,
        ...rest,
      };
      dispatch({
        type: 'user/queryUserList',
        payload: {
          pathParams: {
            id: this.state.selectedOrgKeys[0],
          },
          queryParams: payload,
        },
      });
    });
  };

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      pageIndex: pagination.current,
      pageSize: pagination.pageSize,
      ...formValues,
      ...filters,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    this.searchUsers(params);
    this.setState({
      selectedRows: [],
    });
  };

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };
  handleAddModalVisible = flag => {
    this.setState({
      modalVisible: !!flag,
    });
  };

  handleUpdateModalVisible = (flag, record = {}) => {
    this.setState({
      updateModalVisible: !!flag,
      currentUser: record,
    });
  };

  // 删除按钮
  handleDelete = () => {
    const { dispatch, deleteLoading } = this.props;
    if (deleteLoading) return;
    let ids = this.state.selectedRows.map(s => s.id);
    Modal.confirm({
      title: '删除账号',
      content: '确定删除已选账号？',
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        return dispatch({
          type: 'user/delete',
          payload: {
            data: ids,
          },
        }).then(res => {
          if (res.errorCode === 0) {
            message.success('删除成功');
            this.setState({
              selectedRows: [],
            });
            this.searchUsers();
          }
        });
      },
    });
  };

  // 添加
  handleAdd = fieldsValue => {
    const { dispatch, createLoading } = this.props;
    if (createLoading) return;
    dispatch({
      type: 'user/add',
      payload: {
        data: {
          ...fieldsValue,
          orgs: [
            {
              id: this.state.selectedOrgKeys[0],
            },
          ],
        },
      },
    }).then(res => {
      if (res.errorCode === 0) {
        message.success('添加成功');
        this.handleAddModalVisible();
        this.searchUsers();
      }
    });
  };

  // 锁定
  handleLock = () => {
    const { dispatch, lockLoading } = this.props;
    if (lockLoading) return;
    let ids = this.state.selectedRows.map(s => s.id);
    Modal.confirm({
      title: '锁定账号',
      content: '确定锁定已选账号？',
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        return dispatch({
          type: 'user/lock',
          payload: {
            data: ids,
          },
        }).then(res => {
          if (res.errorCode === 0) {
            message.success('锁定成功');
            this.setState({
              selectedRows: [],
            });
            this.searchUsers();
          }
        });
      },
    });
  };

  // 解锁
  handleUnLock = () => {
    const { dispatch, unlockLoading } = this.props;
    if (unlockLoading) return;
    let ids = this.state.selectedRows.map(s => s.id);
    Modal.confirm({
      title: '解锁账号',
      content: '确定解锁已选账号？',
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        return dispatch({
          type: 'user/unlock',
          payload: {
            data: ids,
          },
        }).then(res => {
          if (res.errorCode === 0) {
            message.success('解锁成功');
            this.setState({
              selectedRows: [],
            });
            this.searchUsers();
          }
        });
      },
    });
  };

  // 重置密码
  handleResetPwd = () => {
    const { dispatch, resetPwdLoading } = this.props;
    if (resetPwdLoading) return;
    let ids = this.state.selectedRows.map(s => s.id);
    Modal.confirm({
      title: '重置密码',
      content: '确定将已选账号重置密码？',
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        return dispatch({
          type: 'user/resetPassword',
          payload: {
            data: ids,
          },
        }).then(res => {
          if (res.errorCode === 0) {
            message.success('重置成功');
            this.setState({
              selectedRows: [],
            });
          }
        });
      },
    });
  };

  // 编辑
  handleUpdate = fieldsValue => {
    const { dispatch, updateLoading } = this.props;
    if (updateLoading) return;
    const { currentUser } = this.state;
    dispatch({
      type: 'user/update',
      payload: {
        pathParams: {
          id: currentUser.id,
        },
        data: {
          ...currentUser,
          ...fieldsValue,
        },
      },
    }).then(res => {
      if (res.errorCode === 0) {
        message.success('更新成功');
        this.handleUpdateModalVisible();
        this.searchUsers();
      }
    });
  };

  handleTreeNodeSelect = (selectedKeys, e) => {
    if (!e.selected) {
      this.searchUsers();
      return;
    }
    this.setState(
      {
        selectedOrgKeys: selectedKeys,
        selectedRows: [],
      },
      this.searchUsers
    );
  };

  canRemove = () => {
    const { selectedRows } = this.state;
    return !selectedRows.some(r => r.isMaster);
  };

  canLock = () => {
    const { selectedRows } = this.state;
    return !selectedRows.every(r => r.isLocked);
  };

  canUnLock = () => {
    const { selectedRows } = this.state;
    return selectedRows.every(r => r.isLocked);
  };

  handleSearch = q => {
    q = q.trim();
    if (q === '' || q == undefined) {
      return;
    }
    return router.push(`/system/user/search?${stringify({ q })}`);
  };

  renderHeader = () => {
    const {
      form: { getFieldDecorator },
      userList,
      cargoTypes,
      productGroups,
      loading,
      orgTree,
    } = this.props;

    const {
      modalVisible,
      updateModalVisible,
      currentUser,
      selectedRows,
      selectedOrgKeys,
    } = this.state;
    return (
      <div className={styles.searchHeader}>
        <div className={styles.title}>用户管理</div>
        <Row type="flex" justify="center" align="middle">
          <Col span={10}>
            {getFieldDecorator('q')(
              <Search
                placeholder="请输入账号/姓名/手机号/邮箱"
                onSearch={this.handleSearch}
                maxLength={30}
                enterButton
              />
            )}
          </Col>
        </Row>
      </div>
    );
  };

  render() {
    const {
      form: { getFieldDecorator },
      userList,
      cargoTypes,
      productGroups,
      loading,
      orgTree,
      createLoading,
      updateLoading,
      deleteLoading,
    } = this.props;

    const {
      modalVisible,
      updateModalVisible,
      currentUser,
      selectedRows,
      selectedOrgKeys,
    } = this.state;

    const parentMethods = {
      handleAdd: this.handleAdd,
      handleAddModalVisible: this.handleAddModalVisible,
    };
    const updateProps = {
      handleUpdateModalVisible: this.handleUpdateModalVisible,
      handleUpdate: this.handleUpdate,
      currentUser,
      orgTree,
    };

    return (
      <PageHeaderWrapper className={styles.userManage} action={this.renderHeader()}>
        <div className={styles.userContent}>
          <div className={styles.tree}>
            <OrgTree
              selectedKeys={selectedOrgKeys}
              orgTree={orgTree}
              onTreeNodeSelect={this.handleTreeNodeSelect}
            />
          </div>
          <Card className={styles.contentInfo} bordered={false}>
            <div className={styles.tableList}>
              <div className={styles.tableListOperator}>
                <IconButton title="添加" icon="icon-add" onClick={this.handleAddModalVisible} />
                {selectedRows.length > 0 && (
                  <Fragment>
                    {this.canRemove() && (
                      <IconButton
                        title="删除"
                        icon="icon-delete"
                        style={{ marginLeft: 10 }}
                        loading={deleteLoading}
                        onClick={() => this.handleDelete()}
                      />
                    )}
                    {this.canLock() && (
                      <IconButton
                        title="锁定"
                        icon="iconoss---suoding"
                        style={{ marginLeft: 10 }}
                        onClick={() => this.handleLock()}
                      />
                    )}
                    {this.canUnLock() && (
                      <IconButton
                        title="解锁"
                        icon="iconoss---jiesuo"
                        style={{ marginLeft: 10 }}
                        onClick={() => this.handleUnLock()}
                      />
                    )}
                    <IconButton
                      title="重置密码"
                      icon="iconoss---zhongzhi"
                      style={{ marginLeft: 10 }}
                      onClick={() => this.handleResetPwd()}
                    />
                  </Fragment>
                )}
              </div>
              <StandardTable
                rowKey="id"
                showCheckbox
                selectedRows={selectedRows}
                loading={loading}
                data={userList}
                columns={this.getColumns()}
                onSelectRow={this.handleSelectRows}
                onChange={this.handleStandardTableChange}
              />
            </div>
          </Card>
        </div>
        <CreateUserForm {...parentMethods} loading={createLoading} modalVisible={modalVisible} />
        <UpdateUserForm
          {...updateProps}
          loading={updateLoading}
          updateModalVisible={updateModalVisible}
        />
      </PageHeaderWrapper>
    );
  }
}

export default Manage;
